package rhc.taskSchedule.taskDistribute.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

import rhc.discribute.node.commander.Commander;
import rhc.discribute.node.host.Host;
import rhc.taskSchedule.commander.TaskScheduleCommanderExecute;
import rhc.taskSchedule.entity.Running;
import rhc.taskSchedule.entity.TaskSchedule;
import rhc.taskSchedule.exception.NodeException;
import rhc.taskSchedule.taskDistribute.StartRunning;

public class TaskScheduleStartRunning extends BasicStartRunning implements StartRunning{

	@Override
	public void startRunning(Running running, TaskScheduleCommanderExecute taskScheduleCommanderExecute) throws Exception {
		
		String runningId=running.getId();
		
		String runNodeLabel=TaskSchedule.RUN_NODE_LABEL;
		Host runNode=getRunNode(runNodeLabel,taskScheduleCommanderExecute);
		
		this.sendRunnning(runningId, runNode, taskScheduleCommanderExecute);
	}

	/**获取该节点标识的节点
	 * @param runNodeLabel
	 * @param taskScheduleCommander
	 * @return
	 * @throws Exception
	 */
	private Host getRunNode(String runNodeLabel,TaskScheduleCommanderExecute taskScheduleCommanderExecute) throws Exception{
		Commander distributeNodeCommander=taskScheduleCommanderExecute.getDistributeNodeCommander();
		
		Set<Host> nodeSet=distributeNodeCommander.getNodeManage().getLabelHostSet(runNodeLabel);
		if(null == nodeSet || nodeSet.isEmpty()){
			throw new NodeException("节点标签 {} 未找到节点",runNodeLabel);
		}
		if(nodeSet.size() == 1){
			return nodeSet.iterator().next();
		}else{
			List<Host> nodeList=new ArrayList<Host>(nodeSet);
			return nodeList.get(new Random().nextInt(nodeList.size()));
		}
	}
	
}
